{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
    "\n",
    "Instructions for setting up Colab are as follows:\n",
    "1. Open a new Python 3 notebook.\n",
    "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n",
    "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
    "4. Run this cell to set up dependencies.\n",
    "\"\"\"\n",
    "# If you're using Google Colab and not running locally, run this cell\n",
    "\n",
    "# install NeMo\n",
    "BRANCH = 'main'\n",
    "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[nlp]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "from nemo.collections import nlp as nemo_nlp\n",
    "from nemo.utils.exp_manager import exp_manager\n",
    "from nemo.utils import logging\n",
    "\n",
    "import os\n",
    "import wget\n",
    "import torch\n",
    "import pytorch_lightning as pl\n",
    "from omegaconf import OmegaConf"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Task Description\n",
    "**Joint Intent and Slot classification** - is a task of classifying an Intent and detecting all relevant Slots (Entities)\n",
    "for this Intent in a query.\n",
    "For example, in the query:  `What is the weather in Santa Clara tomorrow morning?`, we would like to classify the query\n",
    "as a `weather` Intent, and detect `Santa Clara` as a `location` slot and `tomorrow morning` as a `date_time` slot.\n",
    "Intents and Slots names are usually task specific and defined as labels in the training data.\n",
    "This is a fundamental step that is executed in any task-driven Conversational Assistant.\n",
    "\n",
    "Our Bert based model implementation enables to train and then detect both of these tasks together.\n",
    "\n",
    "**Multi Label Joint Intent and Slot classification** - is very similar to the task above, but instead of only classifying a single Intent, the task can predict multiple different intents for each query. For example, for the query `Yes, please tell me the weather`, we might want the intents for this utterance to be `yes` and `weather`. You can skip to that tutorial [here](#multi-label)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Dataset and NeMo data format\n",
    "\n",
    "In this tutorial we are going to use a virtual assistant interaction data set that can be downloaded from here: https://github.com/xliuhw/NLU-Evaluation-Data.\n",
    "There are about 10K training and 1K testing queries which cover 64 various Intents and 55 Slots. \n",
    "\n",
    "To work with NeMo NLP classification model, this dataset should be first converted to the NeMo format, which requires next files:\n",
    "- **dict.intents.csv** - list of all intent names in the data. One line per an intent name.\n",
    "- **dict.slots.csv** - list of all slot names in the data. One line per a slot name. It is possible to use both: B- I- notations, for separating between first and intermediate tokens for multi token slots. Or just use one slot type for each token of multi token slot. Our recommendation is to use later one, since it is simpler and there is no visible degradation in performance.\n",
    "- **train.tsv/test.tsv** - contain original queries, one per line, and intent number separated by tab. For example: `what alarms do i have set right now\t0`. Intent numbers are according to the intent line in the intent dictionary file (dict.intents.csv) starting from 0. First line of these files contains a header line: `sentence \\tab label`.\n",
    "- **train_slot.tvs/test_slot.tsv** - contain one line per a query, where instead each token there is a number of the token from the slots dictionary file (dict.slots.csv), starting from 0. Last 'out-of scope' token is usually located in the last line of the dictionary. Example: `54 0 0 54 54 12 12` (numbers separated by space). No header line in these files.\n",
    "\n",
    "NeMo provides **import_dataset.py** converter for few reference datasets (Assistant / Atis / Snips) which converts them to the NeMo data format for the Intent and Slot classification model. If you have your own annotated dataset in a different format, you will need to write a data converter. Possible recommended format for your own annotation, is to have one text file per all examples of one intent. With one line per query in a form like: `did i set an alarm to [alarm_type : wake up] in the [timeofday : morning]`, using brackets to define slot names. This is very similar to the assistant format from this example and you can use its converter to NeMo format with small changes. \n",
    "\n",
    "You can run this utility as follows:\n",
    "\n",
    "**python examples/nlp/intent_slot_classification/data/import_datasets.py --dataset_name=assistant --source_data_dir=source_dir_name --target_data_dir=target_dir_name**\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Download, preprocess and explore the dataset\n",
    "## Download the dataset and convert it to the NeMo format"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# you can replace DATA_DIR and NEMO_DIR with your own locations\n",
    "DATA_DIR = \".\"\n",
    "NEMO_DIR = '.'\n",
    "\n",
    "# download the converter files from github for the purpose of this tutorial\n",
    "wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/scripts/dataset_processing/nlp/intent_and_slot/import_datasets.py', NEMO_DIR)\n",
    "wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/scripts/dataset_processing/nlp/intent_and_slot/assistant_utils.py', NEMO_DIR)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# download and unzip the example dataset from github\n",
    "print('Downloading dataset...')\n",
    "wget.download('https://github.com/xliuhw/NLU-Evaluation-Data/archive/master.zip', DATA_DIR)\n",
    "! unzip {DATA_DIR}/NLU-Evaluation-Data-master.zip -d {DATA_DIR}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# convert the dataset to the NeMo format\n",
    "!python {NEMO_DIR}/import_datasets.py --dataset_name=assistant --source_data_dir={DATA_DIR}/NLU-Evaluation-Data-master --target_data_dir={DATA_DIR}/nemo_format\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Data exploration\n",
    "You can see the dataset in both the original and NeMo's formats. We have here 65 different Intents and 55 Slots, which could be typical commands for virtual assistants. Out of scope slot has the name 'O' and is the last in the dictionary of Slots. And we can see examples of queries and also format of training intent and slot files. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# list of queries divided by intent files in the original training dataset\n",
    "! ls -l {DATA_DIR}/NLU-Evaluation-Data-master/dataset/trainset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# print all intents from the NeMo format intent dictionary\n",
    "!echo 'Intents: ' $(wc -l < {DATA_DIR}/nemo_format/dict.intents.csv)\n",
    "! cat {DATA_DIR}/nemo_format/dict.intents.csv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# print all slots from the NeMo format slot dictionary\n",
    "!echo 'Slots: ' $(wc -l < {DATA_DIR}/nemo_format/dict.slots.csv)\n",
    "! cat {DATA_DIR}/nemo_format/dict.slots.csv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# examples from the intent training file\n",
    "! head -n 10 {DATA_DIR}/nemo_format/train.tsv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# examples from the slot training file\n",
    "! head -n 10 {DATA_DIR}/nemo_format/train_slots.tsv"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Training model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model configuration\n",
    "\n",
    "Our Joint Intent and Slot classification model is comprised of the pretrained [BERT](https://arxiv.org/pdf/1810.04805.pdf) model with an Intent and Slot Classification layer on top of it.\n",
    "\n",
    "All model and training parameters are defined in the **intent_slot_classification_config.yaml** config file. This file is located in the folder **examples/nlp/intent_slot_classification/conf/**. It contains 2 main sections:\n",
    "- **model**: All arguments that are related to the Model - language model, token classifier, optimizer and schedulers, datasets and any other related information\n",
    "\n",
    "- **trainer**: Any argument to be passed to PyTorch Lightning\n",
    "\n",
    "We will download the config file from repository for the purpose of the tutorial. If you have a version of NeMo installed locally, you can use it from the above folder."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# download the model config file from repository for the purpose of this example\n",
    "wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/intent_slot_classification/conf/intent_slot_classification_config.yaml', NEMO_DIR)\n",
    "\n",
    "# print content of the config file\n",
    "config_file = \"intent_slot_classification_config.yaml\"\n",
    "print(config_file)\n",
    "config = OmegaConf.load(config_file)\n",
    "print(OmegaConf.to_yaml(config))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setting up Data within the config\n",
    "\n",
    "Among other things, the config file contains dictionaries called train_ds and validation_ds. These are configurations used to setup the Dataset and DataLoaders of the corresponding config.\n",
    "\n",
    "The converter utility creates both training and evaluation files in the same directory, so we need to specify `model.data_dir` parameter to this directory. Also notice that some config lines, including `model.data_dir`, have `???` in place of paths, this means that values for these fields are required to be specified by the user.\n",
    "\n",
    "`config.model.intent_loss_weight` parameter - is a balance of training loss between Intent and Slot losses, a number between 0 to 1. Its default value is 0.6 which gives slightly higher priority to the Intent loss and it empirically works quite well. You can experiment with this value if you like.\n",
    "Also you can try to change `config.model.class_balancing` parameter to `weighted_loss` and see if you get better accuracy.\n",
    "\n",
    "Let's now add the data directory path to the config."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "config.model.data_dir = f'{DATA_DIR}/nemo_format'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Building the PyTorch Lightning Trainer\n",
    "\n",
    "NeMo models are primarily PyTorch Lightning modules - and therefore are entirely compatible with the PyTorch Lightning ecosystem. `config.trainer.max_epochs` - param defines number of training epochs. Usually 50-100 epochs or less should be enough to train on your data. Let's instantiate the Trainer object."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# lets modify some trainer configs\n",
    "# checks if we have GPU available and uses it\n",
    "accelerator = 'gpu' if torch.cuda.is_available() else 'cpu'\n",
    "config.trainer.devices = 1\n",
    "config.trainer.accelerator = accelerator\n",
    "\n",
    "config.trainer.precision = 16 if torch.cuda.is_available() else 32\n",
    "\n",
    "# for mixed precision training, uncomment the line below (precision should be set to 16 and amp_level to O1):\n",
    "# config.trainer.amp_level = O1\n",
    "\n",
    "# remove distributed training flags\n",
    "config.trainer.strategy = None\n",
    "\n",
    "# setup a small number of epochs for demonstration purposes of this tutorial\n",
    "config.trainer.max_epochs = 5\n",
    "\n",
    "trainer = pl.Trainer(**config.trainer)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setting up a NeMo Experiment\n",
    "\n",
    "NeMo has an experiment manager that handles logging and checkpointing for us, so let's use it. Model check points during training will be saved in this directory. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "exp_dir = exp_manager(trainer, config.get(\"exp_manager\", None))\n",
    "# the exp_dir provides a path to the current experiment for easy access\n",
    "print(str(exp_dir))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Initializing the model and Training\n",
    "\n",
    "Initial statistics of the dataset will be displayed at the beginning of the training and then Intent and Slot classification report will be displayed after each training epoch."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# initialize the model\n",
    "model = nemo_nlp.models.IntentSlotClassificationModel(config.model, trainer=trainer)\n",
    "\n",
    "# train\n",
    "trainer.fit(model)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "After training for 5 epochs, which should take no more than few minutes, you can expect training precision for this data set to be around these numbers (the accuracy will gradually continue to improve for this dataset up to about 50 epochs of training): \n",
    "```\n",
    "Intents:\n",
    "    label                                                precision    recall       f1           support   \n",
    "    alarm_query (label_id: 0)                               94.74      94.74      94.74         19\n",
    "    alarm_remove (label_id: 1)                             100.00     100.00     100.00         11\n",
    "    alarm_set (label_id: 2)                                 85.71      94.74      90.00         19\n",
    "    audio_volume_down (label_id: 3)                          0.00       0.00       0.00          8\n",
    "    audio_volume_mute (label_id: 4)                        100.00      86.67      92.86         15\n",
    "    audio_volume_up (label_id: 5)                           56.52     100.00      72.22         13\n",
    "    calendar_query (label_id: 6)                            55.00      57.89      56.41         19\n",
    "    calendar_remove (label_id: 7)                           88.89      84.21      86.49         19\n",
    "    calendar_set (label_id: 8)                              81.25      68.42      74.29         19\n",
    "    cooking_recipe (label_id: 9)                            86.36     100.00      92.68         19\n",
    "    datetime_convert (label_id: 10)                          0.00       0.00       0.00          8\n",
    "    datetime_query (label_id: 11)                           65.52     100.00      79.17         19\n",
    "    email_addcontact (label_id: 12)                        100.00      12.50      22.22          8\n",
    "    email_query (label_id: 13)                              83.33      78.95      81.08         19\n",
    "    email_querycontact (label_id: 14)                       62.50      78.95      69.77         19\n",
    "    email_sendemail (label_id: 15)                          70.83      89.47      79.07         19\n",
    "    general_affirm (label_id: 16)                           95.00     100.00      97.44         19\n",
    "    general_commandstop (label_id: 17)                     100.00     100.00     100.00         19\n",
    "    general_confirm (label_id: 18)                         100.00     100.00     100.00         19\n",
    "    general_dontcare (label_id: 19)                        100.00     100.00     100.00         19\n",
    "    general_explain (label_id: 20)                         100.00      94.74      97.30         19\n",
    "    general_joke (label_id: 21)                            100.00     100.00     100.00         12\n",
    "    general_negate (label_id: 22)                           95.00     100.00      97.44         19\n",
    "    general_praise (label_id: 23)                          100.00      94.74      97.30         19\n",
    "    general_quirky (label_id: 24)                           40.00      10.53      16.67         19\n",
    "    general_repeat (label_id: 25)                          100.00     100.00     100.00         19\n",
    "    iot_cleaning (label_id: 26)                             84.21     100.00      91.43         16\n",
    "    iot_coffee (label_id: 27)                               94.74      94.74      94.74         19\n",
    "    iot_hue_lightchange (label_id: 28)                      94.44      89.47      91.89         19\n",
    "    iot_hue_lightdim (label_id: 29)                        100.00      83.33      90.91         12\n",
    "    iot_hue_lightoff (label_id: 30)                         89.47      89.47      89.47         19\n",
    "    iot_hue_lighton (label_id: 31)                           0.00       0.00       0.00          3\n",
    "    iot_hue_lightup (label_id: 32)                          81.25      92.86      86.67         14\n",
    "    iot_wemo_off (label_id: 33)                             60.00     100.00      75.00          9\n",
    "    iot_wemo_on (label_id: 34)                             100.00      14.29      25.00          7\n",
    "    lists_createoradd (label_id: 35)                        78.95      78.95      78.95         19\n",
    "    lists_query (label_id: 36)                              78.95      78.95      78.95         19\n",
    "    lists_remove (label_id: 37)                             90.00      94.74      92.31         19\n",
    "    music_likeness (label_id: 38)                           70.59      66.67      68.57         18\n",
    "    music_query (label_id: 39)                              77.78      73.68      75.68         19\n",
    "    music_settings (label_id: 40)                            0.00       0.00       0.00          7\n",
    "    news_query (label_id: 41)                               77.78      73.68      75.68         19\n",
    "    play_audiobook (label_id: 42)                           90.00      94.74      92.31         19\n",
    "    play_game (label_id: 43)                                80.00      84.21      82.05         19\n",
    "    play_music (label_id: 44)                               53.85      73.68      62.22         19\n",
    "    play_podcasts (label_id: 45)                            89.47      89.47      89.47         19\n",
    "    play_radio (label_id: 46)                               93.75      78.95      85.71         19\n",
    "    qa_currency (label_id: 47)                              95.00     100.00      97.44         19\n",
    "    qa_definition (label_id: 48)                            85.00      89.47      87.18         19\n",
    "    qa_factoid (label_id: 49)                               45.16      73.68      56.00         19\n",
    "    qa_maths (label_id: 50)                                100.00     100.00     100.00         14\n",
    "    qa_stock (label_id: 51)                                 95.00     100.00      97.44         19\n",
    "    recommendation_events (label_id: 52)                    94.44      89.47      91.89         19\n",
    "    recommendation_locations (label_id: 53)                 94.74      94.74      94.74         19\n",
    "    recommendation_movies (label_id: 54)                   100.00     100.00     100.00         10\n",
    "    social_post (label_id: 55)                              90.00      94.74      92.31         19\n",
    "    social_query (label_id: 56)                             94.74     100.00      97.30         18\n",
    "    takeaway_order (label_id: 57)                           93.75      78.95      85.71         19\n",
    "    takeaway_query (label_id: 58)                           85.71      94.74      90.00         19\n",
    "    transport_query (label_id: 59)                          83.33      78.95      81.08         19\n",
    "    transport_taxi (label_id: 60)                          100.00     100.00     100.00         18\n",
    "    transport_ticket (label_id: 61)                         89.47      89.47      89.47         19\n",
    "    transport_traffic (label_id: 62)                       100.00     100.00     100.00         19\n",
    "    weather_query (label_id: 63)                           100.00      89.47      94.44         19\n",
    "    -------------------\n",
    "    micro avg                                               85.04      85.04      85.04       1076\n",
    "    macro avg                                               81.13      80.81      79.36       1076\n",
    "    weighted avg                                            84.10      85.04      83.54       1076\n",
    "    \n",
    "Slots:\n",
    "    label                                                precision    recall       f1           support   \n",
    "    alarm_type (label_id: 0)                                 0.00       0.00       0.00          0\n",
    "    app_name (label_id: 1)                                   0.00       0.00       0.00          6\n",
    "    artist_name (label_id: 2)                                0.00       0.00       0.00         21\n",
    "    audiobook_author (label_id: 3)                           0.00       0.00       0.00          1\n",
    "    audiobook_name (label_id: 4)                             0.00       0.00       0.00         18\n",
    "    business_name (label_id: 5)                             60.00      56.60      58.25         53\n",
    "    business_type (label_id: 6)                              0.00       0.00       0.00         24\n",
    "    change_amount (label_id: 7)                              0.00       0.00       0.00         25\n",
    "    coffee_type (label_id: 8)                                0.00       0.00       0.00          4\n",
    "    color_type (label_id: 9)                                 0.00       0.00       0.00         12\n",
    "    cooking_type (label_id: 10)                              0.00       0.00       0.00          0\n",
    "    currency_name (label_id: 11)                            84.09      75.51      79.57         49\n",
    "    date (label_id: 12)                                     57.95      91.07      70.83        112\n",
    "    definition_word (label_id: 13)                           0.00       0.00       0.00         20\n",
    "    device_type (label_id: 14)                              74.55      51.25      60.74         80\n",
    "    drink_type (label_id: 15)                                0.00       0.00       0.00          0\n",
    "    email_address (label_id: 16)                             0.00       0.00       0.00         14\n",
    "    email_folder (label_id: 17)                              0.00       0.00       0.00          1\n",
    "    event_name (label_id: 18)                              100.00      13.24      23.38         68\n",
    "    food_type (label_id: 19)                                51.72      69.77      59.41         43\n",
    "    game_name (label_id: 20)                                60.00      14.29      23.08         21\n",
    "    game_type (label_id: 21)                                 0.00       0.00       0.00          0\n",
    "    general_frequency (label_id: 22)                         0.00       0.00       0.00          9\n",
    "    house_place (label_id: 23)                              93.33      42.42      58.33         33\n",
    "    ingredient (label_id: 24)                                0.00       0.00       0.00          6\n",
    "    joke_type (label_id: 25)                                 0.00       0.00       0.00          4\n",
    "    list_name (label_id: 26)                                 0.00       0.00       0.00         21\n",
    "    meal_type (label_id: 27)                                 0.00       0.00       0.00          0\n",
    "    media_type (label_id: 28)                                0.00       0.00       0.00         37\n",
    "    movie_name (label_id: 29)                                0.00       0.00       0.00          0\n",
    "    movie_type (label_id: 30)                                0.00       0.00       0.00          0\n",
    "    music_album (label_id: 31)                               0.00       0.00       0.00          0\n",
    "    music_descriptor (label_id: 32)                          0.00       0.00       0.00          3\n",
    "    music_genre (label_id: 33)                               0.00       0.00       0.00          9\n",
    "    news_topic (label_id: 34)                                0.00       0.00       0.00         17\n",
    "    order_type (label_id: 35)                                0.00       0.00       0.00         17\n",
    "    person (label_id: 36)                                   44.86      92.31      60.38         52\n",
    "    personal_info (label_id: 37)                             0.00       0.00       0.00         20\n",
    "    place_name (label_id: 38)                               71.25      77.03      74.03        148\n",
    "    player_setting (label_id: 39)                            0.00       0.00       0.00          1\n",
    "    playlist_name (label_id: 40)                             0.00       0.00       0.00          1\n",
    "    podcast_descriptor (label_id: 41)                        0.00       0.00       0.00         13\n",
    "    podcast_name (label_id: 42)                              0.00       0.00       0.00          4\n",
    "    radio_name (label_id: 43)                               66.67      10.53      18.18         38\n",
    "    relation (label_id: 44)                                  0.00       0.00       0.00         17\n",
    "    song_name (label_id: 45)                                 0.00       0.00       0.00         22\n",
    "    time (label_id: 46)                                     70.27      78.20      74.02        133\n",
    "    time_zone (label_id: 47)                                 0.00       0.00       0.00          9\n",
    "    timeofday (label_id: 48)                                 0.00       0.00       0.00         28\n",
    "    transport_agency (label_id: 49)                          0.00       0.00       0.00          9\n",
    "    transport_descriptor (label_id: 50)                      0.00       0.00       0.00          0\n",
    "    transport_name (label_id: 51)                            0.00       0.00       0.00          4\n",
    "    transport_type (label_id: 52)                           78.38      82.86      80.56         35\n",
    "    weather_descriptor (label_id: 53)                        0.00       0.00       0.00         17\n",
    "    O (label_id: 54)                                        92.42      98.80      95.50       5920\n",
    "    -------------------\n",
    "    micro avg                                               89.10      89.10      89.10       7199\n",
    "    macro avg                                               21.86      18.56      18.18       7199\n",
    "    weighted avg                                            84.42      89.10      86.01       7199\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Evaluation\n",
    "To see how the model performs, we can evaluate the performance of the trained model on a test data file. Here we will reload the model from the `.nemo` file saved during training. By default, the `.nemo` file contains the final checkpoint. We will use the same trainer for testing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# extract the path of the best checkpoint from the training, you may update it to any other saved checkpoint file\n",
    "checkpoint_path = trainer.checkpoint_callback.best_model_path\n",
    "\n",
    "# load the model from this checkpoint\n",
    "eval_model = nemo_nlp.models.IntentSlotClassificationModel.load_from_checkpoint(checkpoint_path=checkpoint_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# we will setup testing data reusing the same config (test section)\n",
    "eval_model.setup_test_data(test_data_config=config.model.test_ds)\n",
    "\n",
    "# run the evaluation on the test dataset\n",
    "trainer.test(model=eval_model, ckpt_path=None, verbose=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Inference from Examples\n",
    "Next step to see how the trained model will classify Intents and Slots for given queries from this domain. To improve the predictions you may need to train the model for more than 5 epochs.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "queries = [\n",
    "    'set alarm for seven thirty am',\n",
    "    'lower volume by fifty percent',\n",
    "    'what is my schedule for tomorrow',\n",
    "]\n",
    "\n",
    "pred_intents, pred_slots = eval_model.predict_from_examples(queries, config.model.test_ds)\n",
    "\n",
    "logging.info('The prediction results of some sample queries with the trained model:')\n",
    "for query, intent, slots in zip(queries, pred_intents, pred_slots):\n",
    "    logging.info(f'Query : {query}')\n",
    "    logging.info(f'Predicted Intent: {intent}')\n",
    "    logging.info(f'Predicted Slots: {slots}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Training Script\n",
    "\n",
    "If you have NeMo installed locally (eg. cloned from the Github), you can also train the model with the example script: `examples/nlp/intent_slot_classification/intent_slot_classification.py.`\n",
    "This script contains an example on how to train, evaluate and perform inference with the IntentSlotClassificationModel.\n",
    "\n",
    "To run a training script, use:\n",
    "\n",
    "`cd examples/nlp/intent_slot_classification`\n",
    "\n",
    "`python intent_slot_classification.py model.data_dir=PATH_TO_DATA_DIR`\n",
    "\n",
    "By default, this script uses examples/nlp/intent_slot_classification/conf/intent_slot_classification_config.py config file, and you may update all the params inside of this config file or alternatively providing them in the command line."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='multi-label'></a>\n",
    "# Multi-Label Intent Classification\n",
    "---\n",
    "\n",
    "As mentioned above, our multi-label model will be very similar the single intent classification model, with the added functionality of predicting multiple different intents for a single query. For example, the query `show all flights and fares from denver to san francisco` would have intents `atis_airfare` and `atis_flight`. From our list of intents found in `dict.intents.csv`, the model checks whether each individual intent is suitable for the given query.\n",
    "\n",
    "For this tutorial, we will be using the ATIS (Airline Travel Information System) dataset, converting it to a multi-label data format, and then using the new data to train our model.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Download the dataset and convert it to the NeMo format"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# download the converter files from github for the purpose of this tutorial\n",
    "DATA_DIR = './multiatis'\n",
    "NEMO_DIR = './atis'\n",
    "\n",
    "!mkdir {DATA_DIR}\n",
    "!mkdir {NEMO_DIR}\n",
    "\n",
    "\n",
    "files = [f'https://raw.githubusercontent.com/howl-anderson/ATIS_dataset/master/data/raw_data/ms-cntk-atis/atis.dict.intent.csv', \n",
    "         f'https://raw.githubusercontent.com/howl-anderson/ATIS_dataset/master/data/raw_data/ms-cntk-atis/atis.dict.slots.csv',\n",
    "         f'https://raw.githubusercontent.com/howl-anderson/ATIS_dataset/master/data/raw_data/ms-cntk-atis/atis.dict.vocab.csv',\n",
    "         f'https://raw.githubusercontent.com/howl-anderson/ATIS_dataset/master/data/raw_data/ms-cntk-atis/atis.test.intent.csv',\n",
    "         f'https://raw.githubusercontent.com/howl-anderson/ATIS_dataset/master/data/raw_data/ms-cntk-atis/atis.test.pkl', \n",
    "         f'https://raw.githubusercontent.com/howl-anderson/ATIS_dataset/master/data/raw_data/ms-cntk-atis/atis.test.query.csv',\n",
    "         f'https://raw.githubusercontent.com/howl-anderson/ATIS_dataset/master/data/raw_data/ms-cntk-atis/atis.test.slots.csv', \n",
    "         f'https://raw.githubusercontent.com/howl-anderson/ATIS_dataset/master/data/raw_data/ms-cntk-atis/atis.train.intent.csv',\n",
    "         f'https://raw.githubusercontent.com/howl-anderson/ATIS_dataset/master/data/raw_data/ms-cntk-atis/atis.train.pkl',\n",
    "         f'https://raw.githubusercontent.com/howl-anderson/ATIS_dataset/master/data/raw_data/ms-cntk-atis/atis.train.query.csv',\n",
    "         f'https://raw.githubusercontent.com/howl-anderson/ATIS_dataset/master/data/raw_data/ms-cntk-atis/atis.train.slots.csv']\n",
    "\n",
    "         \n",
    "for file in files:\n",
    "    wget.download(file, DATA_DIR)\n",
    "\n",
    "\n",
    "# download the converter files from github for the purpose of this tutorial\n",
    "wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/scripts/dataset_processing/nlp/intent_and_slot/import_datasets.py', NEMO_DIR)\n",
    "wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/scripts/dataset_processing/nlp/intent_and_slot/assistant_utils.py', NEMO_DIR)\n",
    "wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/scripts/dataset_processing/nlp/intent_and_slot/convert_datasets.py', NEMO_DIR)\n",
    "\n",
    "# Get original atis dataset\n",
    "!python {NEMO_DIR}/import_datasets.py --dataset_name=atis --source_data_dir={DATA_DIR} --target_data_dir={DATA_DIR}/nemo_format\n",
    "# Script will create new files at {DATA_DIR}/new_format\n",
    "!mkdir {DATA_DIR}/new_format\n",
    "!python {NEMO_DIR}/convert_datasets.py --source_data_dir={DATA_DIR}/nemo_format --target_data_dir={DATA_DIR}/new_format"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Data Augmentation (Optional)\n",
    "---\n",
    "\n",
    "In scenarios when we don't have many training examples with multiple intent labels, data augmentation can be very useful. This can be done by concatenating utterances together, and adding it to our training data. Some ways of concatenating include adding a period or \\\"and\\\" between the two utterances. A script has been provided below to help with augmentation, but it can be changed depending on your use case."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# download the data augmentation script\n",
    "wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/scripts/dataset_processing/nlp/intent_and_slot/augment_training_data.py', NEMO_DIR)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The script augment_training_data.py allows for four command line arguments to be passed in: \n",
    "\n",
    "source_data_dir: directory that contains the original multi-label data <br>\n",
    "target_data_dir: directory to store the new data directory <br>\n",
    "num_mixed: number of new utterances to add to dataset per class pair (utterances with labels 1 and 2) <br>\n",
    "link_string: string that is in between the two utterances (\".\", \"\", \"and\", \"with\") <br>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!python {NEMO_DIR}/augment_training_data.py --source_data_dir={DATA_DIR}/new_format --target_data_dir={DATA_DIR}/augmented_data --num_mixed=10"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Training the Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# download the model config file from repository for the purpose of this example\n",
    "wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/intent_slot_classification/conf/multi_label_intent_slot_classification_config.yaml', NEMO_DIR)\n",
    "\n",
    "# print content of the config file\n",
    "config_file = f\"{NEMO_DIR}/multi_label_intent_slot_classification_config.yaml\"\n",
    "print(config_file)\n",
    "config = OmegaConf.load(config_file)\n",
    "print(OmegaConf.to_yaml(config))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "config.model.data_dir = f\"{DATA_DIR}/new_format\"\n",
    "config.model.validation_ds.prefix = \"dev\"\n",
    "config.model.test_ds.prefix = \"dev\"\n",
    "config.model.class_balancing = \"weighted_loss\"\n",
    "config.trainer.max_epochs = 5\n",
    "run_name = \"test\"\n",
    "\n",
    "# checks if we have GPU available and uses it\n",
    "cuda = 1 if torch.cuda.is_available() else 0\n",
    "config.trainer.gpus = cuda\n",
    "config.trainer.precision = 16 if torch.cuda.is_available() else 32\n",
    "\n",
    "# remove distributed training flags\n",
    "config.trainer.accelerator = None\n",
    "\n",
    "trainer = pl.Trainer(**config.trainer)\n",
    "config.exp_manager.exp_dir = os.path.join(DATA_DIR, \"output/\" + run_name)\n",
    "config.exp_manager.create_checkpoint_callback = True\n",
    "\n",
    "exp_dir = exp_manager(trainer, config.get(\"exp_manager\", None))\n",
    "model = nemo_nlp.models.MultiLabelIntentSlotClassificationModel(config.model, trainer=trainer)\n",
    "trainer.fit(model)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Evaluation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To see how the model performs, we can evaluate the performance of the trained model on a test data file. Here we will reload the model from the `.nemo` file saved during training. By default, the `.nemo` file contains the final checkpoint. We will use the same trainer for testing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# specify checkpoint path with .nemo file\n",
    "checkpoint_path = os.path.join(exp_dir, \"checkpoints\", \"MultiLabelIntentSlot.nemo\")\n",
    "\n",
    "# load the model from this checkpoint\n",
    "eval_model =  nemo_nlp.models.MultiLabelIntentSlotClassificationModel.restore_from(checkpoint_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Optimizing Threshold\n",
    "\n",
    "As mentioned above, when classifiying a given query such as `show all flights and fares from denver to san francisco`, our model checks whether each individual intent would be suitable. Before assigning the final labels for a query, the model assigns a probability an intent matches the query. For example, if our `dict.intents.csv` had 5 different intents, then the model could output for a given query \\[0.52, 0.38, 0.21, 0.67. 0.80\\] where each value represents the probability that query matches that particular intent. \n",
    "\n",
    "We need to use these probabilities to generate final label predictions of 0 or 1 for each label. While we can use 0.5 as the probability threshold, it is usually the case that there is a better threshold to use depending on the metric we want to optimize. For this tutorial, we will be finding the threshold that gives us the best micro-F1 score on the validation set. After running the `optimize_threshold` method, the threshold attribute for our model will be updated."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "eval_model.optimize_threshold(config.model.test_ds, 'dev')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "eval_model.threshold"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  Inference from Examples\n",
    "Similar to the previous example we can run inference to see how the trained model will classify Intents and Slots for given queries from this domain. To improve the predictions you may need to train the model for more than 10 epochs.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "queries = [\n",
    "    'i would like to find a flight from charlotte to las vegas that makes a stop in st. louis',\n",
    "    'on april first i need a ticket from tacoma to san jose departing before 7 am',\n",
    "    'how much is the limousine service in boston',\n",
    "]\n",
    "\n",
    "# We use the optimized threshold for predictions\n",
    "pred_intents, pred_slots, pred_list = eval_model.predict_from_examples(queries, config.model.test_ds)\n",
    "logging.info('The prediction results of some sample queries with the trained model:')\n",
    "    \n",
    "for query, intent, slots in zip(queries, pred_intents, pred_slots):\n",
    "    logging.info(f'Query : {query}')\n",
    "    logging.info(f'Predicted Intents: {intent}')\n",
    "    logging.info(f'Predicted Slots: {slots}')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
